package com.yiyoucheng.controller;

import com.yiyoucheng.pojo.Department;
import com.yiyoucheng.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 部门信息查询
 */
@RestController
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    //部门层级关系查询
    @GetMapping("/findAll")
    public List<Department> findDepartment(){
        //数据库中所有的部门集合
        List<Department> depList = departmentService.findAll();
        //查询最顶层的部门信息,其父id为0
        List<Department> topDepartmentList = departmentService.findByPid(0);
        //设置部门层级关系,并返回拥有完整层级关系的部门
        List<Department> departmentList = new ArrayList<>();
        for (Department topDepartment : topDepartmentList) {
            Department department = setDepartmentTree(depList, topDepartment);
            departmentList.add(department);
        }
        return departmentList;
    }

    /**
     * 设置部门层级关系
     * @param depList 所有的部门信息
     * @param parDepartment 父级部门
     */
    public Department setDepartmentTree(List<Department> depList,Department parDepartment){
        //存储子部门的集合
        List<Department> childDepartmentList = new ArrayList<Department>();
        //遍历所有的部门
        for (Department department : depList) {
            //当部门列表里有部门的父id是传进来的部门的id时
            if(department.getParentId() == parDepartment.getId()){
                //把当前部门添加到父部门的子部门集合里
                childDepartmentList.add(department);
                //递归设置下一级部门层级关系
                setDepartmentTree(depList,department);
            }
        }
        //当前部门子部门不为空时
        if(childDepartmentList.size() > 0 && childDepartmentList != null){
            //设置父部门的子部门列表
            parDepartment.setChildrenDepartmentList(childDepartmentList);
        }
        //把设置好所有层级关系的部门返回
        return parDepartment;
    }
}
